import * as express from 'express'
import { Request, Response } from 'express'
import { failure, success } from "../utils/responses";
import { BadRequest } from "http-errors";
import { authService } from "../services/auth";
import { User } from "../entities/User";

const router = express.Router();

/**
 * 华为用户一键登录返回接口
 */
export interface HuaweiUserInfo {
  openID: string
  unionID: string
  loginMobileNumber: string // 华为账号绑定号码
  loginMobileValid: number
  purePhoneNumber: string
  phoneCountryCode: string
}

export interface tokenInfoRequest {
  access_token: string;
}

/**
 * 获取用户级凭证返回结果接口
 */
export interface HuaweiTokenResponse {
  access_token: string;
  refresh_token: string;
  expires_in: number;
  token_type: string;
  id_token?: string;
  scope?: string;
}

enum LoginType {
  phoneAndVerifyCode = 1,
  HuaweiAccount = 2
}

/**
 * 用户登录
 * POST /auth/login
 */
router.post("/login", async (req: Request, res: Response) => {
    try {
      // 接收前端给我发来的code授权码
      const { code, type } = req.body;
      if (!code) throw new BadRequest('授权码不能为空');
      if (!type) throw new BadRequest('登录方式不能为空');

      let user: User
      if (type === LoginType.phoneAndVerifyCode) {
        // 手机号验证码登录
        const phoneNumber = code as string
        user = await authService.getUserByPhoneNumber(phoneNumber)
      } else if (type === LoginType.HuaweiAccount) {
        // 华为账号登录
        // 获取用户凭证（AccessToken、IdToken、RefreshToken）
        const tokenData = await authService.getToken(code);
        console.info('tokenData: ' + tokenData)

        const accessToken = tokenData.access_token;
        console.info('华为访问令牌获取成功,idToken: ' + tokenData.id_token);

        // 获取用户信息
        const userInfo = await authService.getUserInfo({ access_token: accessToken });
        user = await authService.getUserByUnionId(userInfo)
      } else {
        throw new BadRequest('没有该登录方式');
      }

      // 登录成功，应根据id生成token并返回给前端
      const token = authService.generateToken(user.id)

      // 返回token
      success(res, '登录成功', token)
    } catch (error) {
      failure(res, error);
    }
  }
)

export default router
